package AnalysisApi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import dbConn.DBconn;

public class API {
	
	public static JSONObject json1 =new JSONObject();
    //public static fileInfo v = new fileInfo();
//	public static void main(String[] args) throws Exception 
//	{
////      String test = "[{\"version\":\"eosio_abi/1.0\",\"types\":[{\"new_type_name\":\"name\",\"type\":\"name\"}],\"structs\":[{\"name\":\"create\",\"base\":\"\",\"fields\":[{\"name\":\"issuer\",\"type\":\"name\"},{\"name\":\"maximum_supply\",\"type\":\"asset\"}]},{\"name\":\"issue\",\"base\":\"\",\"fields\":[{\"name\":\"to\",\"type\":\"name\"},{\"name\":\"quantity\",\"type\":\"asset\"},{\"name\":\"memo\",\"type\":\"string\"}]},{\"name\":\"retire\",\"base\":\"\",\"fields\":[{\"name\":\"quantity\",\"type\":\"asset\"},{\"name\":\"memo\",\"type\":\"string\"}]},{\"name\":\"close\",\"base\":\"\",\"fields\":[{\"name\":\"owner\",\"type\":\"name\"},{\"name\":\"symbol\",\"type\":\"symbol\"}]},{\"name\":\"transfer\",\"base\":\"\",\"fields\":[{\"name\":\"from\",\"type\":\"name\"},{\"name\":\"to\",\"type\":\"name\"},{\"name\":\"quantity\",\"type\":\"asset\"},{\"name\":\"memo\",\"type\":\"string\"}]},{\"name\":\"account\",\"base\":\"\",\"fields\":[{\"name\":\"balance\",\"type\":\"asset\"}]},{\"name\":\"currency_stats\",\"base\":\"\",\"fields\":[{\"name\":\"supply\",\"type\":\"asset\"},{\"name\":\"max_supply\",\"type\":\"asset\"},{\"name\":\"issuer\",\"type\":\"name\"}]}],\"actions\":[{\"name\":\"transfer\",\"type\":\"transfer\",\"ricardian_contract\":\"\"},{\"name\":\"issue\",\"type\":\"issue\",\"ricardian_contract\":\"\"},{\"name\":\"retire\",\"type\":\"retire\",\"ricardian_contract\":\"\"},{\"name\":\"create\",\"type\":\"create\",\"ricardian_contract\":\"\"},{\"name\":\"close\",\"type\":\"close\",\"ricardian_contract\":\"\"}],\"tables\":[{\"name\":\"accounts\",\"type\":\"account\",\"index_type\":\"i64\",\"key_names\":[\"currency\"],\"key_types\":[\"uint64\"]},{\"name\":\"stat\",\"type\":\"currency_stats\",\"index_type\":\"i64\",\"key_names\":[\"currency\"],\"key_types\":[\"uint64\"]}],\"ricardian_clauses\":[],\"abi_extensions\":[]}]";
////      String test2 = "[{\"version\":\"eosio_ab3/1.0\",\"types\":[{\"new_type_name\":\"name\",\"type\":\"name\"}],\"structs\":[{\"name\":\"create\",\"base\":\"\",\"fields\":[{\"name\":\"issuer\",\"type\":\"name\"},{\"name\":\"maximum_supply\",\"type\":\"asset\"}]},{\"name\":\"issue\",\"base\":\"\",\"fields\":[{\"name\":\"to\",\"type\":\"name\"},{\"name\":\"quantity\",\"type\":\"asset\"},{\"name\":\"memo\",\"type\":\"string\"}]},{\"name\":\"retire\",\"base\":\"\",\"fields\":[{\"name\":\"quantity\",\"type\":\"asset\"},{\"name\":\"memo\",\"type\":\"string\"}]},{\"name\":\"close\",\"base\":\"\",\"fields\":[{\"name\":\"owner\",\"type\":\"name\"},{\"name\":\"symbol\",\"type\":\"symbol\"}]},{\"name\":\"transfer\",\"base\":\"\",\"fields\":[{\"name\":\"from\",\"type\":\"name\"},{\"name\":\"to\",\"type\":\"name\"},{\"name\":\"quantity\",\"type\":\"asset\"},{\"name\":\"memo\",\"type\":\"string\"}]},{\"name\":\"account\",\"base\":\"\",\"fields\":[{\"name\":\"balance\",\"type\":\"asset\"}]},{\"name\":\"currency_stats\",\"base\":\"\",\"fields\":[{\"name\":\"supply\",\"type\":\"asset\"},{\"name\":\"max_supply\",\"type\":\"asset\"},{\"name\":\"issuer\",\"type\":\"name\"}]}],\"actions\":[{\"name\":\"transfer\",\"type\":\"transfer\",\"ricardian_contract\":\"\"},{\"name\":\"issue\",\"type\":\"issue\",\"ricardian_contract\":\"\"},{\"name\":\"retire\",\"type\":\"retire\",\"ricardian_contract\":\"\"},{\"name\":\"create\",\"type\":\"create\",\"ricardian_contract\":\"\"},{\"name\":\"close\",\"type\":\"close\",\"ricardian_contract\":\"\"}],\"tables\":[{\"name\":\"accounts\",\"type\":\"account\",\"index_type\":\"i64\",\"key_names\":[\"currency\"],\"key_types\":[\"uint64\"]},{\"name\":\"stat\",\"type\":\"currency_stats\",\"index_type\":\"i64\",\"key_names\":[\"currency\"],\"key_types\":[\"uint64\"]}],\"ricardian_clauses\":[],\"abi_extensions\":[]}]";
//  	//读取ABI文件
//	String filePath1="src/main/resources/abiv1.json";
//	String filePath2="src/main/resources/abiv2.json";
//	String path_dir ="src/main/resources/";
//	JSON_begin(filePath1,filePath2,path_dir);
//
//  }

    public static void JSON_begin(String filename1,String filename2,String path_dir) throws  Exception{
    	  	FileUtils fUtils =new FileUtils();
    	  	StringBuffer sb1 =new StringBuffer();
        ArrayList<String> s1= fUtils.readFromTextFile(filename1);
    			for (int i=0;i<s1.size();i++){
    		        sb1.append(s1.get(i));
    		    }
    			System.out.println(sb1);
    			String test = sb1.toString();

        StringBuffer sb2 =new StringBuffer();
        ArrayList<String> s= fUtils.readFromTextFile(filename2);
        for (int i=0;i<s.size();i++){
            sb2.append(s.get(i));
        }
        System.out.println(sb2);
        String test2 = sb2.toString();

        Object json = JSON.parse(test);
        if (json instanceof JSONObject) {
            dvide_object(test,"/Users/xianglin/lynnxiang/testPrj/test_abi/base.txt");
        } else if (json instanceof JSONArray) {
            dvide_array(test,"/Users/xianglin/lynnxiang/testPrj/test_abi/base.txt");
        } else {
            System.out.println("no type");
        }
        Object json2 = JSON.parse(test2);
        if (json2 instanceof JSONObject) {
            dvide_object(test2,"/Users/xianglin/lynnxiang/testPrj/test_abi/di.txt");
        } else if (json2 instanceof JSONArray) {
            dvide_array(test2,"/Users/xianglin/lynnxiang/testPrj/test_abi/di.txt");
        } else {
            System.out.println("no type");
        }
        //readFile02();
        //JSONObject json1 =new JSONObject();
        //compare("/Users/xianglin/lynnxiang/testPrj/test_abi/base.txt","/Users/xianglin/lynnxiang/testPrj/test_abi/di.txt");
        compareSame("/Users/xianglin/lynnxiang/testPrj/test_abi/base.txt","/Users/xianglin/lynnxiang/testPrj/test_abi/di.txt");
        getFilemodifydate("/Users/xianglin/lynnxiang/testPrj/test_abi/base.txt");
        //deleteFile("src/main/resources/base.txt");
        //deleteFile("src/main/resources/di.txt");

        //新增比较数据信息
        
	  	
	  	
	  	json1.put("filename", "ABI");
	  	json1.put("filepath", path_dir);
	  	json1.put("basesize", getFileSize(path_dir));
	  	json1.put("cmpsize", getFileSize(filename2));
	  	
	   
        DBconn.setAbiInfo(json1);
        System.out.println("新增成功");
    }

	public static int getFileSize(String filename) {
        File file = new File(filename);
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在");
            return -1;
        }
        return (int) file.length();
    }
	
  public static boolean dvide_object(String source,String filename) {
      JSONObject Json = JSONObject.parseObject(source);
      List list = new ArrayList();
      for (Object key : Json.keySet()) {
          Object value_object = Json.get(key);
          String val = value_object.toString();
          if (key.toString() == "version") {
              try {
                  API.writeFile02((key+":"+val),filename);
              }catch (Exception e)
              {

                }
                continue;
            }
            Object val_ob = JSON.parse(val);
            if (val_ob instanceof JSONArray) {
                JSONArray fromOBjectarray = JSONArray.parseArray(val);
                for (int i = 0; i < fromOBjectarray.size(); i++) {
                    JSONObject everyjb = fromOBjectarray.getJSONObject(i);
                    String val_use = everyjb.toString();
                    switch (key.toString()) {
                        case "types":
                            types typesFromJson = JsonUtils.parseJsonToObj(val_use, types.class);
                            //System.out.println("----"+typesFromJson);
                            try {
                                API.writeFile02((typesFromJson.toString()),filename);

                            }catch (Exception e){}//System.out.println("types");
                            break;
                        case "structs":
                        	//structs structsFromJson = JSON.parseObject(val_use, structs.class);
                            structs structsFromJson = JsonUtils.parseJsonToObj(val_use, structs.class);
                            //JsonUtils.parseObjToJson(object)
                            System.out.println(structsFromJson);
                            try {
                                API.writeFile02((structsFromJson.toString()),filename);

                            }catch (Exception e){
                            	System.out.println("Error: struct can`t acess fastjson!");
                            }//System.out.println("types");
                            //System.out.println("structs");
                            break;
                        case "actions":
                            actions actionsFromJson = JsonUtils.parseJsonToObj(val_use, actions.class);
                            //System.out.println(actionsFromJson);
                            try {
                                API.writeFile02((actionsFromJson.toString()),filename);

                            }catch (Exception e){}//System.out.println("types");
                            //System.out.println("actions");
                            break;
                        case "tables":
                            tables tablesFromJson = JsonUtils.parseJsonToObj(val_use, tables.class);
                            //System.out.println(tablesFromJson);
                            try {
                                API.writeFile02((tablesFromJson.toString()),filename);

                            }catch (Exception e){}//System.out.println("types");
                            //System.out.println("tables");
                            break;
                        case "abi_extensions":
                            abi_extensions abi_extensionsFromJson = JsonUtils.parseJsonToObj(val_use, abi_extensions.class);
                            //System.out.println(abi_extensionsFromJson);
                            try {
                                API.writeFile02((abi_extensionsFromJson.toString()),filename);

                            }catch (Exception e){}//System.out.println("types");
                            //System.out.println("tables");
                            break;
                        case "ricardian_clauses":
                            ricardian_clauses ricardian_clausesFromJson = JsonUtils.parseJsonToObj(val_use, ricardian_clauses.class);
                            //System.out.println(ricardian_clausesFromJson);
                            try {
                                API.writeFile02((ricardian_clausesFromJson.toString()),filename);

                            }catch (Exception e){}//System.out.println("types");
                            //System.out.println("tables");
                            break;
                        default:
                            System.out.println("error:" + key.toString());
                            //test.writeFile02(structsFromJson.toString());
                            break;
                    }
                }
                if (fromOBjectarray.size() == 0) {
                    System.out.println(key + ":" + val);
                    try {
                        API.writeFile02((key + ":" + val),filename);

                    }catch (Exception e){}//System.out.println("types");

                }
            } else if (val_ob instanceof JSONObject) {
                //Object val_use =
                String val_use = val.substring(1, val.lastIndexOf("]"));
                switch (key.toString()) {
                    case "types":
                        types typesFromJson = JsonUtils.parseJsonToObj(val_use, types.class);
                        System.out.println(typesFromJson);
                        //System.out.println("types");
                        break;
                    case "structs":
                        structs structsFromJson = JsonUtils.parseJsonToObj(val_use, structs.class);
                        System.out.println(structsFromJson);
                        //System.out.println("structs");
                        break;
                    case "actions":
                        actions actionsFromJson = JsonUtils.parseJsonToObj(val_use, actions.class);
                        System.out.println(actionsFromJson);
                        //System.out.println("actions");
                        break;
                    case "tables":
                        tables tablesFromJson = JsonUtils.parseJsonToObj(val_use, tables.class);
                        System.out.println(tablesFromJson);
                        //System.out.println("tables");
                        break;
                    case "abi_extensions":
                        abi_extensions abi_extensionsFromJson = JsonUtils.parseJsonToObj(val_use, abi_extensions.class);
                        System.out.println(abi_extensionsFromJson);
                        //System.out.println("tables");
                        break;
                    case "ricardian_clauses":
                        ricardian_clauses ricardian_clausesFromJson = JsonUtils.parseJsonToObj(val_use, ricardian_clauses.class);
                        System.out.println(ricardian_clausesFromJson);
                        //System.out.println("tables");
                        break;
                    default:
                        System.out.println("error:" + key.toString());
                        break;
                }
                System.out.println(key.toString());
            } else {
                Map map = new Hashtable();
                map.put(key, val);
                list.add(map);
            }

        }

        return false;

    }

    public static boolean dvide_array(String source,String filename) {
        JSONArray fromOBjectarray = JSONArray.parseArray(source);
        for (int i = 0; i < fromOBjectarray.size(); i++) {
            Object everyjb = fromOBjectarray.getJSONObject(i);
            String str = everyjb.toString();
            dvide_object(str,filename);
            System.out.println("  ");

      }
      return false;
  }
  public static void getFilemodifydate(String filename)
  {
      File file =new File(filename);
      long time = file.lastModified();

      Date d = new Date(time);
      Format simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
      String dateString = simpleFormat.format(d);
      json1.put("modifyTime", dateString);
      //v.setModify_time(dateString);
      //System.out.println(dateString);
  }

    public static void writeFile02(String arrs,String filepath) throws Exception {

        FileOutputStream fos = new FileOutputStream(new File(filepath),true);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(arrs + "\t\n");
        bw.close();
        osw.close();
        fos.close();

    }
    public static void readFile02() throws Exception {
        FileInputStream fis = new FileInputStream("src/main/resources/aaa.txt");
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);

        String line = "";
        String arrs = null;
        while ((line = br.readLine()) != null) {
            arrs = line;
            System.out.println(arrs);
        }
        br.close();
        isr.close();
        fis.close();
    }

    public static void compare(String filename,String filename2)throws Exception
    {
        FileInputStream fis = new FileInputStream(filename);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        FileInputStream fis2 = new FileInputStream(filename2);
        InputStreamReader isr2 = new InputStreamReader(fis2, "UTF-8");
        BufferedReader br2 = new BufferedReader(isr2);
        ArrayList list =new ArrayList<String>();
        ArrayList list2 =new ArrayList<String>();

        String line = "";
        String arrs = null;
        while ((line = br.readLine()) != null) {
            arrs = line;
            //System.out.println(arrs);
            list.add(arrs);
        }

      String line2 ="";
      String arrs2 =null;
      while ((line2 = br2.readLine()) != null) {
          arrs2 = line2;
          //System.out.println(arrs);
          list2.add(arrs2);
      }
      String difference_s1 ="";
      String difference_s2 ="";
      
      if(list.size()>list2.size())
      {
          for(Object s:list) {
              int a = 0;
              if(s.toString().contains("version"))
              {
                  String[] s1_version = s.toString().split(":");
                  json1.put("baseversion", s1_version[1]);
                  //v.setBase_version(s1_version[1]);
              }
              for (Object s2 : list2) {
                  if(s.toString().contains("version"))
                  {
                      String[] s2_version = s2.toString().split(":");
                      json1.put("cmpversion", s2_version[1]);
                      //v.setCompasre_version(s2_version[1]);
                  }
                  if (s.equals(s2)) {
                      a++;
                  }else{
                     if(s.toString().contains(s2.toString())){
//                    	 difference_s2=s.toString().replace(s2.toString(),"");  
                     }
                  }
              }
              if (a != 0) {
                  System.out.println("String("+s+")has same String");
              }else {
                  System.out.println("String"+s+"has unsame String");
                  difference_s2 =difference_s2+s.toString();

              }
          }
      }else{
          for(Object s2:list2)
          {
              int a = 0;
              if(s2.toString().contains("version"))
              {
                  String[] s2_version = s2.toString().split(":");
                  json1.put("cmpversion", s2_version[1]);
                  //v.setCompasre_version(s2_version[1]);
              }
              for (Object s : list) {
                  if(s.toString().contains("version"))
                  {
                      String[] s1_version = s.toString().split(":");
                      json1.put("baseversion", s1_version[1]);
                      //v.setBase_version(s1_version[1]);
                  }
                  if (s.equals(s2)) {
                      a++;
                  }else {
//                      difference_s1 =s2.toString().replace(s.toString(),""); 
                  }
              }
              if (a != 0) {
                  System.out.println("String("+s2+")has same String");
              }else {
                  System.out.println("String("+s2+")has unsame String");
                  //存入数据库
                  difference_s1 =difference_s1+s2.toString();
              }
          }
      }
      json1.put("difference", difference_s1+";"+difference_s2);
      //v.setDifference(difference_s1+";"+difference_s2);


      br.close();
      isr.close();
      fis.close();
      br2.close();
      isr2.close();
      fis2.close();
  }

    
    public static void compareSame(String filename,String filename2)throws Exception
    {
        FileInputStream fis = new FileInputStream(filename);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        FileInputStream fis2 = new FileInputStream(filename2);
        InputStreamReader isr2 = new InputStreamReader(fis2, "UTF-8");
        BufferedReader br2 = new BufferedReader(isr2);
        ArrayList list =new ArrayList<String>();
        ArrayList list2 =new ArrayList<String>();

        String line = "";
        String arrs = null;
        while ((line = br.readLine()) != null) {
            arrs = line;
            //System.out.println(arrs);
            list.add(arrs);
        }

      String line2 ="";
      String arrs2 =null;
      while ((line2 = br2.readLine()) != null) {
          arrs2 = line2;
          //System.out.println(arrs);
          list2.add(arrs2);
      }
      String difference_s1 ="";
      String difference_s2 ="";
      
      if(list.size()>list2.size())
      {
          for(Object s:list) {
              int a = 0;
              if(s.toString().contains("version"))
              {
                  String[] s1_version = s.toString().split(":");
                  json1.put("baseversion", s1_version[1]);
                  //v.setBase_version(s1_version[1]);
              }
              for (Object s2 : list2) {
                  if(s.toString().contains("version"))
                  {
                      String[] s2_version = s2.toString().split(":");
                      json1.put("cmpversion", s2_version[1]);
                      //v.setCompasre_version(s2_version[1]);
                  }
                  if (s.equals(s2)) {
                      a++;
                  }else{
                     if(s.toString().contains(s2.toString())){
//                    	 difference_s2=s.toString().replace(s2.toString(),"");  
                     }
                  }
              }
              if (a != 0) {
                  System.out.println("String("+s+")has same String");
                  difference_s2 =difference_s2+s.toString();
              }else {
                  System.out.println("String"+s+"has unsame String");
                  //difference_s2 =difference_s2+s.toString();

              }
          }
      }else{
          for(Object s2:list2)
          {
              int a = 0;
              if(s2.toString().contains("version"))
              {
                  String[] s2_version = s2.toString().split(":");
                  json1.put("cmpversion", s2_version[1]);
                  //v.setCompasre_version(s2_version[1]);
              }
              for (Object s : list) {
                  if(s.toString().contains("version"))
                  {
                      String[] s1_version = s.toString().split(":");
                      json1.put("baseversion", s1_version[1]);
                      //v.setBase_version(s1_version[1]);
                  }
                  if (s.equals(s2)) {
                      a++;
                  }else {
//                      difference_s1 =s2.toString().replace(s.toString(),""); 
                  }
              }
              if (a != 0) {
                  System.out.println("String("+s2+")has same String");
                  difference_s1 =difference_s1+s2.toString();
              }else {
                  System.out.println("String("+s2+")has unsame String");
                  //存入数据库
                  //difference_s1 =difference_s1+s2.toString();
              }
          }
      }
      json1.put("difference", difference_s1+";"+difference_s2);
      //json1.put("difference", "please ignore this data due to under debug!!!");
      //v.setDifference(difference_s1+";"+difference_s2);


      br.close();
      isr.close();
      fis.close();
      br2.close();
      isr2.close();
      fis2.close();
  }

    public static boolean deleteFile(String pathname){
        boolean result = false;
        File file = new File(pathname);
        if (file.exists()) {
            file.delete();
            result = true;
            System.out.println("文件已经被成功删除");
        }
        return result;
    }


}

